package cn.codeforfun.client.data;

import cn.codeforfun.client.constants.DiscoveryServiceProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class DataContext implements DiscoveryClient {
    private Map<String, List<cn.codeforfun.client.data.ServiceInstance>> instances = new HashMap<>();
    @Resource
    DataHandler dataHandler;
    @Resource
    DiscoveryServiceProperties discoveryServiceProperties;

    @Override
    public String description() {
        return null;
    }

    @Override
    public List<ServiceInstance> getInstances(String serviceId) {
        List<cn.codeforfun.client.data.ServiceInstance> serviceInstances = instances.get(serviceId);
        if (ObjectUtils.isEmpty(serviceInstances)) {
            refreshServiceInstances();
            serviceInstances = instances.get(serviceId);
        }
        if (ObjectUtils.isEmpty(serviceInstances)) {
            return new ArrayList<>();
        }
        return serviceInstances.stream().map(s -> new ServiceInstance() {
            @Override
            public String getServiceId() {
                return s.getName();
            }

            @Override
            public String getHost() {
                return s.getHost();
            }

            @Override
            public int getPort() {
                return s.getPort();
            }

            @Override
            public boolean isSecure() {
                return false;
            }

            @Override
            public URI getUri() {
                return URI.create("http://" + s.getHost() + ":" + s.getPort());
            }

            @Override
            public Map<String, String> getMetadata() {
                return new HashMap<>();
            }
        }).collect(Collectors.toList());
    }

    @Override
    public List<String> getServices() {
        return new ArrayList<>(this.instances.keySet());
    }

    private void refreshServiceInstances() {
        Integer serviceActiveTimeout = discoveryServiceProperties.getServiceActiveTimeout();
        List<cn.codeforfun.client.data.ServiceInstance> serviceInstanceList = dataHandler.findServiceInstanceList(serviceActiveTimeout);
        refreshServiceInstances(serviceInstanceList);
    }

    public void refreshServiceInstances(List<cn.codeforfun.client.data.ServiceInstance> serviceInstanceList) {
        this.instances = serviceInstanceList.stream().collect(Collectors.groupingBy(cn.codeforfun.client.data.ServiceInstance::getName));
    }
}
